using System;
using System.Reflection;
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace EntityKit.Runtime
{
    public static partial class BindService
    {
        private static void BindCollection(Component component, Type type, BindingFlags flags)
        {
            foreach (var field in GetFieldsWithCache(type, flags))
            {
                BindCollection(component, field);
            }
        }

        private static void BindCollection(Component component, FieldInfo field)
        {
            var bindAttr = GetCustomAttributeWithCache<CollectionBindAttribute>(field);
            if (bindAttr == null) return;
            var parent = FindTransformWithPathCache(component.transform, bindAttr.ParentPath);
            if (parent == null)
            {
                Debug.LogError($"集合绑定失败：路径 {bindAttr.ParentPath} 未找到父对象");
                return;
            }
            
            var children = new List<Transform>();
            for (var i = 0; i < parent.childCount; i++)
            {
                var child = parent.GetChild(i);
                if (string.IsNullOrEmpty(bindAttr.ChildNamePattern) || Regex.IsMatch(child.name, bindAttr.ChildNamePattern))
                {
                    children.Add(child);
                }
            }
            
            if (!string.IsNullOrEmpty(bindAttr.SortComparer))
            {
                if (!SortChildren(children, bindAttr.SortComparer))
                {
                    Debug.LogWarning($"集合绑定警告：未知的排序类型 {bindAttr.SortComparer}，将使用默认顺序");
                }
            }
            
            if (field.FieldType.IsArray)
            {
                var elementType = field.FieldType.GetElementType();
                if (elementType == null) 
                {
                    Debug.LogError($"集合绑定失败：无法确定数组元素类型");
                    return;
                }
                var array = Array.CreateInstance(elementType, children.Count);

                for (var i = 0; i < children.Count; i++)
                {
                    var childComponent = children[i].GetComponent(elementType);
                    if (childComponent != null)
                    {
                        array.SetValue(childComponent, i);
                    }
                }
                field.SetValue(component, array);
            }
            else if (field.FieldType.IsGenericType && (field.FieldType.GetGenericTypeDefinition() == typeof(List<>)))
            {
                var elementType = field.FieldType.GetGenericArguments()[0];
                var listType = typeof(List<>).MakeGenericType(elementType);
                var list = Activator.CreateInstance(listType) as System.Collections.IList;

                foreach (var childComponent in children.Select(child => child.GetComponent(elementType)).Where(childComponent => childComponent != null))
                {
                    list?.Add(childComponent);
                }

                field.SetValue(component, list);
            }
            else
            {
                Debug.LogError($"集合绑定失败：字段类型 {field.FieldType.Name} 不支持集合绑定，仅支持数组和List<>类型");
            }
        }
        
        private static bool SortChildren(List<Transform> children, string sortComparer)
        {
            switch (sortComparer.ToLower())
            {
                case "name":
                    children.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.Ordinal));
                    return true;
                case "name_desc":
                    children.Sort((a, b) => string.Compare(b.name, a.name, StringComparison.Ordinal));
                    return true;
                default:
                    return false;
            }
        }
    }
}